package com.rambo.androidnews.slice;

import com.rambo.androidnews.ArticleDetailAbility;
import com.rambo.baselib.BaseAbilitySlice;
import com.rambo.baselib.ResourceTable;
import com.rambo.baselib.constant.ParamConstant;
import com.rambo.baselib.distribute.DeviceSelector;
import com.rambo.baselib.distribute.SelectDeviceResultListener;
import com.rambo.baselib.util.Loading;
import com.rambo.baselib.util.LogUtil;
import com.rambo.baselib.util.ToastUtil;
import ohos.aafwk.ability.continuation.ExtraParams;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Component;
import ohos.agp.components.webengine.*;
import ohos.agp.utils.TextAlignment;
import ohos.bundle.IBundleManager;
import ohos.distributedschedule.interwork.DeviceInfo;
import ohos.media.image.PixelMap;
import ohos.multimodalinput.event.KeyEvent;

public class ArticleDetailAbilitySlice extends BaseAbilitySlice {


    WebView webView;
    String linkUrl;
    DeviceSelector deviceSelector;

    @Override
    protected int getLayoutResId() {
        return ResourceTable.Layout_ability_web_view;
    }

    @Override
    protected void getParamsByIntent(Intent intent) {
        super.getParamsByIntent(intent);
        linkUrl = intent.getStringParam(ParamConstant.LINK_URL);

    }


    @Override
    protected void initView() {
        super.initView();
        webView = (WebView) findComponentById(ResourceTable.Id_web_view);
        showLoading();
        webView.getWebConfig().setJavaScriptPermit(true);
        webView.load(linkUrl);
        toolbarHolder.setDefaultRightOneIcon(ResourceTable.Media_share_24)
                .setDefaultRightOneIconClick(new Component.ClickedListener() {
                    @Override
                    public void onClick(Component component) {
                        ToastUtil.toast("=======分享========");
                        if (deviceSelector != null)
                            deviceSelector.showDistributeDevices(new String[]{
                                    ExtraParams.DEVICETYPE_SMART_PAD, ExtraParams.DEVICETYPE_SMART_TV
                            }, null);
                    }
                });
        //查询是否已授权
        if (verifySelfPermission(ParamConstant.PERMISSION_DATASYN) != IBundleManager.PERMISSION_GRANTED) {
            //是否可以继续弹框授权
            if (canRequestPermission(ParamConstant.PERMISSION_DATASYN)) {
                if (getAbility() instanceof ArticleDetailAbility) {
                    ((ArticleDetailAbility) getAbility()).requestPermissionDataSyn(this);
                }
            }
        } else {
            initDistributeDevice();
        }
    }

    public void initDistributeDevice() {
        deviceSelector = new DeviceSelector();
        deviceSelector.setUp(getAbility());
        deviceSelector.setSelectDeviceResultListener(new SelectDeviceResultListener() {
            @Override
            public void onSuccess(DeviceInfo info) {
                Intent intent = new Intent();
                Operation operation = new Intent.OperationBuilder()
                        .withDeviceId(info.getDeviceId())
                        .withBundleName(getBundleName())
                        .withAbilityName(ArticleDetailAbility.class.getName())
                        .withFlags(Intent.FLAG_ABILITYSLICE_MULTI_DEVICE)
                        .build();
                intent.setOperation(operation);
                intent.setParam(ParamConstant.LINK_URL, linkUrl);
                startAbility(intent);

            }

            @Override
            public void onFail(DeviceInfo info) {
                ToastUtil.toast("拉起失败");
            }
        });

    }

    String loadUrl;

    @Override
    protected void registerClick() {
        super.registerClick();
        webView.setBrowserAgent(new BrowserAgent(this) {
            @Override
            public void onTitleUpdated(WebView webView, String value) {
                super.onTitleUpdated(webView, value);
                toolbarHolder.setDefaultTitle(value);
            }

            @Override
            public void onProgressUpdated(WebView webView, int newValue) {
                super.onProgressUpdated(webView, newValue);
                if (newValue == 0) {
                    loading.updateLoadState(Loading.LoadingState.LOADING);
                } else if (newValue >= 100) {
                    loading.updateLoadState(Loading.LoadingState.SUCCESS);
                }
            }
        });
        webView.setWebAgent(new WebAgent() {
            @Override
            public boolean isNeedLoadUrl(WebView webView, ResourceRequest request) {
                return true;
//                return super.isNeedLoadUrl(webView, request);
            }

            @Override
            public void onLoadingPage(WebView webView, String url, PixelMap icon) {
                super.onLoadingPage(webView, url, icon);
                loading.updateLoadState(Loading.LoadingState.LOADING);
                loadUrl = url;
            }

            @Override
            public void onError(WebView webView, ResourceRequest request, ResourceError error) {
                super.onError(webView, request, error);
                loading.updateLoadState(Loading.LoadingState.FAIL);
            }

            @Override
            public void onPageLoaded(WebView webView, String url) {
                super.onPageLoaded(webView, url);
                loading.updateLoadState(Loading.LoadingState.SUCCESS);
            }
        });
    }

    @Override
    protected void reloadData() {
        super.reloadData();
        webView.load(loadUrl);
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent keyEvent) {
        if (keyCode == KeyEvent.KEY_BACK) {
            Navigator navigator = webView.getNavigator();
            if (navigator.canGoBack()) {
                navigator.goBack();
                return true;
            }
        }
        return super.onKeyUp(keyCode, keyEvent);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (deviceSelector != null)
            deviceSelector.destroy();
        LogUtil.e(TAG + "======onStop======");
    }
}
